package com.ntd.study.pro.zx.cbpp;

import cn.hutool.core.codec.Base64;
import org.apache.commons.lang.ArrayUtils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.*;
import java.security.*;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;


public class RSAUtil {
	public static final String KEY_ALGORITHM = "RSA";   
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
	public static final String CHARSET = "GB18030";
	/**
	 * 字节数据转字符串专用集合
	 */
	private static final char[] HEX_CHAR= {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};


	public static RSAPrivateKey getMerPrivateKey() throws Exception{
		InputStream is=new FileInputStream(CfgLoader.properties.getProperty("MERPEM"));
		return RSAUtil.loadPrivateKey(is);
	}

	public static RSAPublicKey getMerPublicKey() throws Exception{
		InputStream is=new FileInputStream(CfgLoader.properties.getProperty("MERCER"));
		return RSAUtil.generatePublicKeyX509(is);
	}

	public static RSAPrivateKey getCITICPrivateKey() throws Exception{
		InputStream is=new FileInputStream(CfgLoader.properties.getProperty("CITICPEM"));
		return RSAUtil.loadPrivateKey(is);
	}

	public static RSAPublicKey getCITICPublicKey() throws Exception{
		InputStream is=new FileInputStream(CfgLoader.properties.getProperty("CITICCER"));
		return RSAUtil.generatePublicKeyX509(is);
	}

	/**
	 * x.509公钥证书
	 * @throws Exception
	 */
	public static RSAPublicKey generatePublicKeyX509(InputStream is) throws Exception{
		CertificateFactory cf = CertificateFactory.getInstance("X.509");
		X509Certificate x = (X509Certificate)cf.generateCertificate(is);
		PublicKey pk = x.getPublicKey();
		return (RSAPublicKey) pk;
	}

	/**
	 * 从文件中加载私钥
	 * @param keyFileName 私钥文件名
	 * @return 是否成功
	 * @throws Exception 
	 */
	public static RSAPrivateKey loadPrivateKey(InputStream in) throws Exception{
		try {
			BufferedReader br= new BufferedReader(new InputStreamReader(in));
			String readLine= null;
			StringBuilder sb= new StringBuilder();
			while((readLine= br.readLine())!=null){
				if(readLine.charAt(0)=='-'){
					continue;
				}else{
					sb.append(readLine);
					sb.append('\r');
				}
			}
			return loadPrivateKey(sb.toString());
		} catch (IOException e) {
			throw new Exception("私钥数据读取错误");
		} catch (NullPointerException e) {
			throw new Exception("私钥输入流为空");
		}
	}

	public static RSAPrivateKey loadPrivateKey(String privateKeyStr) throws Exception{
		try {
			byte[] buffer= Base64.decode(privateKeyStr);
			PKCS8EncodedKeySpec keySpec= new PKCS8EncodedKeySpec(buffer);
			KeyFactory keyFactory= KeyFactory.getInstance("RSA");
			return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
//			this.privateKey= (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
//			this._strPrivateKey = this.getStringPrivateKey();
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("无此算法");
		} catch (InvalidKeySpecException e) {
			throw new Exception("私钥非法");
		} catch (NullPointerException e) {
			throw new Exception("私钥数据为空");
		}
//		catch (IOException e) {
//			throw new Exception("私钥数据内容读取错误");
//		}
	}
	public static String getStringPublicKey(RSAPublicKey publicKey){
		byte [] bts = publicKey.getEncoded();
		return Base64.encode(bts);
	}
	public static String getStringPrivateKey(RSAPrivateKey privateKey){
		byte [] bts = privateKey.getEncoded();
		return Base64.encode(bts);
	}
	
	public static String encrypt(RSAPublicKey publicKey, String orgmsg, String charset) throws Exception{
		return encrypt(publicKey, orgmsg.getBytes(charset));
	}
	/**
	 * 公钥加密过程
	 * @param publicKey 公钥
	 * @param plainTextData 明文数据
	 * @return
	 * @throws Exception 加密过程中的异常信息
	 */
	public static String encrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception{
		if(publicKey== null){
			throw new Exception("加密公钥为空, 请设置");
		}
		Cipher cipher= null;
		try {
			cipher= Cipher.getInstance("RSA");
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			
			//超过117字节报错，分段加密
			byte[] enbyte=null;
//			StringBuilder sb=new StringBuilder();
			for(int i=0;i<plainTextData.length;i+=64){
				
				byte[] output= cipher.doFinal(ArrayUtils.subarray(plainTextData,i,i+64));				
				enbyte = ArrayUtils.addAll(enbyte, output);
			}
				
			return Base64.encode(enbyte);
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("无此加密算法");
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
			return null;
		}catch (InvalidKeyException e) {
			throw new Exception("加密公钥非法,请检查");
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
			throw new Exception("明文长度非法");
		} catch (BadPaddingException e) {
			throw new Exception("明文数据已损坏");
		}
	}

	public static String decrypt(RSAPrivateKey privateKey, String codeCipherData, String charset) throws Exception{
		byte[] en = decrypt(privateKey, codeCipherData);
		return new String(en, charset);
	}
	/**
	 * 私钥解密过程
	 * @param privateKey 私钥
	 * @param cipherData 密文数据
	 * @return 明文
	 * @throws Exception 解密过程中的异常信息
	 */
	public static byte[]  decrypt(RSAPrivateKey privateKey, String codeCipherData) throws Exception{
		if (privateKey== null){
			throw new Exception("解密私钥为空, 请设置");
		}
		Cipher cipher= null;
		try {
			cipher= Cipher.getInstance("RSA");
			cipher.init(Cipher.DECRYPT_MODE, privateKey);
			//分段解密
			byte[] debyte=null;
			byte[] data=Base64.decode(codeCipherData);
			for(int i=0;i<data.length;i+=128){
				byte[] output= cipher.doFinal(ArrayUtils.subarray(data,i,i+128));
				debyte=ArrayUtils.addAll(debyte, output);
			}
			
			return debyte;
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("无此解密算法");
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
			return null;
		}catch (InvalidKeyException e) {
			e.printStackTrace();
			throw new Exception("解密私钥非法,请检查");
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
			throw new Exception("密文长度非法");
		} catch (BadPaddingException e) {
			e.printStackTrace();
			throw new Exception("密文数据已损坏");
		}		
	}

	public static String byteArrayToCode(byte[] data){
		return Base64.encode(data);
	}
	public static byte[] codeToByteArray(String data) throws IOException{
		return Base64.decode(data);
	}
	/**
	 * 字节数据转十六进制字符串
	 * @param data 输入数据
	 * @return 十六进制内容
	 */
	public static String byteArrayToString(byte[] data){
		StringBuilder stringBuilder= new StringBuilder();
		for (int i=0; i<data.length; i++){
			//取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移
			stringBuilder.append(HEX_CHAR[(data[i] & 0xf0)>>> 4]);
			//取出字节的低四位 作为索引得到相应的十六进制标识符
			stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);
			if (i<data.length-1){
				stringBuilder.append(' ');
			}
		}
		return stringBuilder.toString();
	}

	/**
	 * 签名
	 * @param data
	 * @param privateKey
	 * @return
	 * @throws Exception
	 */
	 public static String sign(String data, String privateKey) {
		 try {
			 byte[] keyBytes = decode64(privateKey);
		        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);		        
		        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		        PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
		        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);		        
		        signature.initSign(privateK);
		        signature.update(data.getBytes(CHARSET));
		        return Base64.encode(signature.sign());
//		        return encode(signature.sign());
		 } catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException("签名失败");
		 }
	    }
	 public static String sign(RSAPrivateKey privKey, String data) throws Exception{
		 try {
		        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);		        
		        signature.initSign(privKey);
		        signature.update(data.getBytes(CHARSET));
		        return Base64.encode(signature.sign());
		 } catch (Exception e) {
				e.printStackTrace();
				throw new Exception("签名失败");
		 }
	    }
	 
	 public static String sign(RSAPrivateKey privKey, String data, String charset) throws Exception{
		 return sign(privKey, data.getBytes(charset));
	 }
	 public static String sign(RSAPrivateKey privKey, byte[] data) throws Exception{
		 try {
		        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);		        
		        signature.initSign(privKey);
		        signature.update(data);
		        return Base64.encode(signature.sign());
		 } catch (Exception e) {
				e.printStackTrace();
				throw new Exception("签名失败");
		 }
	    }
	 /**
	  * 验证
	  * @param data
	  * @param publicKey
	  * @param sign
	  * @return
	  * @throws Exception
	  */
	    public static boolean verify(String data, String publicKey, String sign) {
	    	 try {
	    		 byte[] keyBytes = decode64(publicKey);
	    	        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
	    	        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
	    	        PublicKey publicK = keyFactory.generatePublic(keySpec);
			        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);			        
	    	        signature.initVerify(publicK);
	    	        signature.update(data.getBytes(CHARSET));
	    	        return signature.verify(decode64(sign));
	    	 } catch (Exception e) {
					e.printStackTrace();
					throw new RuntimeException("验证签名失败");
			 }
	    }
	    public static boolean verify(RSAPublicKey pk, String data, String sign, String charset) {
	    	try {
	    		return verify(pk, data.getBytes(charset), sign);
	    	}catch(Exception e){
	    		e.printStackTrace();
				throw new RuntimeException("验证签名失败");
	    	}
	    }
	    public static boolean verify(RSAPublicKey pk, byte[] data, String sign) {
	    	 try {
			        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);			        
	    	        signature.initVerify(pk);
	    	        signature.update(data);
	    	        return signature.verify(decode64(sign));
	    	 } catch (Exception e) {
					e.printStackTrace();
					throw new RuntimeException("验证签名失败");
			 }
	    }
	    
	    public static boolean verify(RSAPublicKey pk, String data, String sign) {
	    	 try {
			        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);			        
	    	        signature.initVerify(pk);
	    	        signature.update(data.getBytes(CHARSET));
	    	        return signature.verify(decode64(sign));
	    	 } catch (Exception e) {
					e.printStackTrace();
					throw new RuntimeException("验证签名失败");
			 }
	    }
	    
	    public static byte[] decode64(String base64) throws Exception {
	    	return Base64.decode(base64);
	    }
	     
	    public static String encode64(byte[] bytes) throws Exception {
	    	return Base64.encode(bytes);
	    }
	    
}
